<?php

namespace App\Controllers;

use App\Models\Relation_model;
use CodeIgniter\Debug\Exceptions;

class user extends BaseController
{
    // 当前用户信息
    private $user_fields = [
        "profile", "male", 'location', 'birthday',
        'start_learn_time', 'end_learn_time', 'school', 'subject', 'qualification',
        'start_work_time', 'company', 'position', 'industry'
    ];

    // 登录用户

    public function index()
    {
        $data = [];
        if ($this->is_login()) {
            $u_id = $this->session->get("u_id");
            $user_field = array_merge([
                "username", "telephone", "email", "avatar", "valid_qualification",
                'follow_count', 'fans_count',"zan_count"
            ], $this->user_fields);
            $result = $this->user_model->getUser("id", $u_id, $user_field);
            if (!$result) {
                print_r($this->json_result(false, '数据库查询失败', $data));
                return;
            }
            $data = $result;
            print_r($this->json_result(true, '查询成功', $data));
        } else {
            print_r($this->json_result(false, '查询失败', $data));
        }
    }

    public function login()
    {
        $data['username'] = '';
        if (!$_POST || empty($this->request->getPost())) {
            print_r($this->json_result(false, '提交为空', $data));
            return;
        }

        $this->validation->setRule('username', '登录名', 'trim|strip_tags|required|min_length[3]|max_length[10]');//设置登录名的验证规则
        $this->validation->setRule('password', '登录密码', 'trim|strip_tags|required|min_length[6]|max_length[10]');//设置登录密码的验证规则

        if (!$this->validation->withRequest($this->request)->run()) {
            $data["errors"] = $this->validation->getErrors();
            print_r($this->json_result(false, '表单验证未通过', $data));
            return;
        }

        $username = $this->request->getPost('username');
        $password = md5($this->request->getPost('password'));
        if (!$username || !$password) {
            print_r($this->json_result(false, '表单为空', $data));
            return;
        }
        $data['username'] = $username;
        $user_info = $this->user_model->login($username, $password);
        $u_id = $user_info['id'];
        $data['u_id'] = $user_info['id'];
        if ($this->is_login()) {
            print_r($this->json_result(true, '用户已经登录', $data));
            return;
        }

        if ($user_info) {
            $user_data = array(
                'u_id' => $u_id,
                'username' => $user_info['username'],
            );
            $this->session->set($user_data);

            print_r($this->json_result(true, '登录成功', $data));
        } else {
            print_r($this->json_result(false, '账号密码不对', $data));
        }
    }

    public function logout()
    {
        $data['username'] = '';
        if ($this->is_login()) {
            $data['username'] = $this->session->username;
            $this->session->remove(['u_id', 'username']);
            print_r($this->json_result(true, '登出成功', $data));
        } else {
            print_r($this->json_result(false, '无效登出', $data));
        }
    }

    public function get_other()
    {
        $data = [];
        $u_id = $this->request->getGet("u_id");
        if (!$u_id) {
            print_r($this->json_result(false, '参数为空', $data));
            return;
        }

        $result = $this->user_model->getUser("id", $u_id, [
            "username", "avatar", "profile", "male",
            'location', 'birthday',
            'start_work_time', 'company', 'position', 'industry',
            'follow_count', 'fans_count',"zan_count"
        ]);
        if (!$result) {
            print_r($this->json_result(false, '数据库查询失败', $data));
            return;
        }

        $data = $result;
        print_r($this->json_result(true, '查询成功', $data));
    }

    // 改名字
    public function update_username(){
        $data["errors"] = '';
        $u_id = $this->session->get("u_id");
        $this->validation->setRule('username', '用户名', 'trim|strip_tags|required|min_length[3]|max_length[10]');
        if (!$this->validation->withRequest($this->request)->run()) {

            $data["errors"] = $this->validation->getErrors();
            print_r($this->json_result(false, '表单验证未通过', $data));
            return;
        }
        $username = $this->request->getPost(["username"]);
        if($this->user_model->query_user('username', $username)) {
            print_r($this->json_result(false, '用户名重复', $data));
            return;
        }
        if (!$this->user_model->update_data($u_id, ["username" =>$username])) {
            print_r($this->json_result(false, '更改失败', $data));
            return;
        }
        print_r($this->json_result(true, '更新成功', $data));
    }

    // 改密码
    public function update_password(){
        $data["errors"] = '';
        $u_id = $this->session->get("username");
        $code = $this->session->get("code");
        if(!$u_id||!$code){
            print_r($this->json_result(false, '没有邮箱验证码', $data));
            return;
        }

        $this->validation->setRule('password', '秘密', 'trim|strip_tags|required|min_length[3]|max_length[10]');
        if (!$this->validation->withRequest($this->request)->run()) {
            $data["errors"] = $this->validation->getErrors();
            print_r($this->json_result(false, '表单验证未通过', $data));
            return;
        }
        $password = md5($this->request->getPost("password"));

        if (!$this->user_model->update_data($u_id, ["password" =>$password])) {
            print_r($this->json_result(false, '更改失败', $data));
            return;
        }
        print_r($this->json_result(true, '更新成功', $data));
    }

    // 更新
    public function update_user()
    {
        $data['errors'] = '';
        $data['update_field'] = [];
        if (!$_POST || empty($this->request->getPost())) {
            print_r($this->json_result(false, '提交为空', $data));
            return;
        }
        $u_id = $this->session->get("u_id");

        $this->validation->setRule('profile', '个人简介', 'permit_empty|max_length[50]');

        $this->validation->setRule('male', '性别', 'permit_empty|greater_than[0]|less_than[3]');
        $this->validation->setRule('location', '位置', 'permit_empty|max_length[10]');
        $this->validation->setRule('birthday', '生日', 'permit_empty|valid_date');

        $this->validation->setRule('start_learn_time', '入学时间', 'permit_empty|valid_date');
        $this->validation->setRule('end_learn_time', '入学时间', 'permit_empty|valid_date');
        $this->validation->setRule('school', '学校', 'permit_empty|max_length[10]');
        $this->validation->setRule('qualification', '学历', 'permit_empty|max_length[10]');
        $this->validation->setRule('subject', '专业', 'permit_empty|max_length[10]');

        $this->validation->setRule('start_work_time', '开始工作时间', 'permit_empty|valid_date');
        $this->validation->setRule('company', '公司', 'permit_empty|max_length[10]');
        $this->validation->setRule('position', '职位', 'permit_empty|max_length[10]');
        $this->validation->setRule('industry', '行业', 'permit_empty|max_length[10]');
        if (!$this->validation->withRequest($this->request)->run()) {

            $data["errors"] = $this->validation->getErrors();
            print_r($this->json_result(false, '表单验证未通过', $data));
            return;
        }
        $change_fields = $this->get_change_fields();
        if (empty($change_fields)) {
            $data["errors"] = $this->validation->getErrors();
            print_r($this->json_result(false, '新增数据为空', $data));
            return;
        }

        if (!$this->user_model->update_data($u_id, $change_fields)) {
            print_r($this->json_result(false, '新增数据为空', $data));
            return;
        }
        $data["update_field"] = array_keys($change_fields);
        print_r($this->json_result(true, '更新数据成功', $data));
    }

    // 拿到改变的字段
    private function get_change_fields()
    {
        $change_fields = [];
        foreach ($this->user_fields as $field) {
            $value = $this->request->getPost($field);
            if (!empty($value))
                $change_fields[$field] = $value;
        }
        return $change_fields;
    }

    // 关注
    public function follow()
    {
        $data['error'] = "";
        $to_id = $this->request->getGet("target_id");
        $u_id = $this->session->get("u_id");
        if(!$to_id || !$u_id ){
            print_r($this->json_result(false, 'id未填入', $data));
            return;
        }

        if($to_id == $u_id) {
            print_r($this->json_result(false, '不能关注自己', $data));
            return;
        }

        if(!$this->user_model->query_user("id",$to_id)){
            print_r($this->json_result(false, '关注对象不存在', $data));
            return;
        }
        $relation_model = new Relation_model();
        if($relation_model->check_is_exist($u_id,$to_id,"follow")){
            print_r($this->json_result(false, '不能重复操作', $data));
            return;
        }
        try{
            // 开始数据库操作
            $relation_model->db->transStart();
            if (!$relation_model->add_new($u_id, $to_id,"follow")){
                print_r($this->json_result(false, '关注失败', $data));
                return;
            }
            $builder = $relation_model->db->table("users");
            $builder->set('follow_count', 'follow_count+1', FALSE);
            $builder->where("id",$u_id);
            $builder->update();
            $builder->set('fans_count', 'fans_count+1', FALSE);
            $builder->where("id",$to_id);
            $builder->update();
            $relation_model->db->transComplete();
            print_r($this->json_result(true, '关注成功', $data));
        }catch (\Exception $exception){
            $data["error"] = $exception->getMessage();
            print_r($this->json_result(false, '关注失败', $data));
            return;
        }
    }

    // 取消关注
    public function unfollow(){
        $data['error'] = "";
        $to_id = $this->request->getGet("target_id");
        $u_id = $this->session->get("u_id");
        if(!$this->user_model->query_user("id",$u_id)){
            print_r($this->json_result(false, '目标不存在', $data));
            return;
        }
        $relation_model = new Relation_model();
        if(!$relation_model->check_is_exist($u_id,$to_id,"follow")){
            print_r($this->json_result(false, '没有关注该用户', $data));
            return;
        }
        try{
            $relation_model->db->transStart();
            if (!$relation_model->delete_old($u_id, $to_id,"follow")) {
                print_r($this->json_result(false, '取关失败', $data));
                return;
            }
            $builder = $relation_model->db->table("users");
            $builder->set('follow_count', 'follow_count-1', FALSE);
            $builder->where("id",$u_id);
            $builder->update();
            $builder->set('fans_count', 'fans_count-1', FALSE);
            $builder->where("id",$to_id);
            $builder->update();
        }catch (\Exception $exception){
            $data["error"] = $exception->getMessage();
            print_r($this->json_result(false, '取关失败', $data));
        }
        $relation_model->db->transComplete();
        print_r($this->json_result(true, '取关成功', $data));
    }

    public function get_follow_list(){
        $data["follow_list"] = [];
        $u_id = $this->request->getGet("target_id");

        if(!$u_id) {
            print_r($this->json_result(false, '目标不存在', $data));
            return;
        }

        $page = $this->request->getGet('page');
        $per_page = $this->request->getGet('per_page');
        $page = is_null($page) ? 0:$page;
        $per_page = is_null($per_page) ? 10:$per_page;
        $relation_model = new Relation_model();
        $data['total_rows'] = $relation_model->db->table($relation_model->table)
            ->where([
                "u_id"=>$u_id,
                "type"=>"follow"
            ])->countAll();
        $data['per_page'] = $per_page;
        $data['page'] = $page;
        $result = $relation_model->get_list("u_id",$u_id,"follow",$per_page,$page);

        // 构造用户数据
        foreach ($result as $row){
            $u_id = $row["to_id"];
            $data["follow_list"][$u_id] = $this->user_model->getUser("id",$u_id,["id","username", "avatar"]);
        }
        print_r($this->json_result(true, '返回成功', $data));
    }

    public function get_fans_list(){
        $data["fans_list"] = [];
        $u_id = $this->request->getGet("target_id");
        if(!$u_id) {
            print_r($this->json_result(false, '目标不存在', $data));
            return;
        }
        $page = $this->request->getGet('page');
        $per_page = $this->request->getGet('per_page');
        $page = is_null($page) ? 0:$page;
        $per_page = is_null($per_page) ? 10:$per_page;

        $relation_model = new Relation_model();
        $data['total_rows'] = $relation_model->db->table($relation_model->table)->where([
            "to_id"=>$u_id,
            "type"=>"follow"
        ])->countAllResults();
        $data['per_page'] = $per_page;
        $data['page'] = $page;

        $result = $relation_model->get_list("to_id",$u_id,"follow",$per_page,$page);
        // 构造用户数据
        foreach ($result as $row){
            $u_id = $row["u_id"];
            $data["fans_list"][$u_id] = $this->user_model->getUser("id",$u_id,["id","username", "avatar"]);
        }
        print_r($this->json_result(true, '返回成功', $data));
    }
}